/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.thrift.server;

import com.google.gson.Gson;
import com.vng.zing.survey.data.AnswersData;
import com.vng.zing.survey.data.IDSurveyData;
import com.vng.zing.survey.data.IDUserResponseData;
import com.vng.zing.survey.data.SurveyData;
import com.vng.zing.survey.data.SurveyStatsData;
import com.vng.zing.survey.data.ResponseData;
import com.vng.zing.survey.thrift.model.AnswerItem;
import com.vng.zing.survey.thrift.model.Error;
import com.vng.zing.survey.thrift.model.IDSurveyItem;
import com.vng.zing.survey.thrift.model.IDSurveyResult;
import com.vng.zing.survey.thrift.model.IDUserResponseItem;
import com.vng.zing.survey.thrift.model.QuesType;
import com.vng.zing.survey.thrift.model.Question;
import com.vng.zing.survey.thrift.model.QuestionStats;
import com.vng.zing.survey.thrift.model.Response;
import com.vng.zing.survey.thrift.model.ResponseKey;
import com.vng.zing.survey.thrift.model.ShortInfoSurveyItem;
import com.vng.zing.survey.thrift.model.State;
import com.vng.zing.survey.thrift.model.SurveyItem;
import com.vng.zing.survey.thrift.model.SurveyItemResult;
import com.vng.zing.survey.thrift.model.SurveyStatsItem;
import com.vng.zing.survey.thrift.model.SurveyStatsResult;
import com.vng.zing.survey.thrift.service.SurveyService.Iface;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.thrift.TException;

/**
 *
 * @author kienpd
 */
public class SurveyServiceHandler implements Iface {

    @Override
    public IDSurveyResult newSurvey(int idUser, SurveyItem surveyItem) throws TException {
        Gson gson = new Gson();
        System.out.println(gson.toJson(surveyItem));
        IDSurveyResult dSurveyResult = new IDSurveyResult();
        IDSurveyItem idSurveyItem = IDSurveyData.getInstance().getIDSurveyItem(idUser);
        List<Integer> listIDList;
        if (idSurveyItem == null) {
            idSurveyItem = new IDSurveyItem();
            listIDList = new ArrayList<>();
        } else {
            listIDList = idSurveyItem.getIdSurveys();
        }
        int maxid = IDSurveyData.getInstance().getMaxIDSurvey();
        if (maxid == 0) {
            dSurveyResult.setError(Error.ERR_SYSTEM);
            return dSurveyResult;
        }
        if (IDSurveyData.getInstance().setMaxIDSurvey(maxid + 1) == Error.ERR_SYSTEM) {
            dSurveyResult.setError(Error.ERR_SYSTEM);
            return dSurveyResult;

        }
        listIDList.add(0, maxid);
        idSurveyItem.setIdSurveys(listIDList);
        idSurveyItem.setCount(idSurveyItem.getCount() + 1);
        if (IDSurveyData.getInstance().setIDSurveyItem(idUser, idSurveyItem) == Error.ERR_SYSTEM) {
            dSurveyResult.setError(Error.ERR_SYSTEM);
            return dSurveyResult;
        }
        if (SurveyData.getInstance().setSurvey(maxid, surveyItem) != Error.SUCCESS) {
            dSurveyResult.setError(Error.ERR_SYSTEM);
            return dSurveyResult;
        }

        SurveyStatsItem surveyStatsItem = new SurveyStatsItem();
        surveyStatsItem.setView(0);
        surveyStatsItem.setResponse(0);
        surveyStatsItem.setIDUser(idUser);
        SurveyStatsData.getInstance().setSurveyStatsItem(maxid, surveyStatsItem);
        dSurveyResult.setError(Error.SUCCESS);
        dSurveyResult.setIdSurvey(maxid);
        return dSurveyResult;
        //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Error newResponse(int idUser, int idSurvey, Response response) throws TException {
        //store response
        IDUserResponseItem dUserResponseItem;
        List<Integer> listIDUser;
        List<AnswerItem> listAnswer = response.getAnswers();
        int idQues = response.getIdUser();
        for (AnswerItem answer : listAnswer) {
            if (AnswersData.getInstance().setAnswer(idUser, idSurvey, idQues, answer) != Error.SUCCESS) {
                return Error.ERR_SYSTEM;
            }
            if (answer.require == false) {
                dUserResponseItem = IDUserResponseData.getInstance().getIDUserResQuesNoRequi(idSurvey,answer.getIdQues());
                if (dUserResponseItem == null) {
                    dUserResponseItem = new IDUserResponseItem();
                    listIDUser = new ArrayList<Integer>();
                } else {
                    listIDUser = dUserResponseItem.getIdUsers();
                }
                listIDUser.add(0, idUser);
                dUserResponseItem.setIdUsers(listIDUser);
                if (IDUserResponseData.getInstance().setIDUserResQuesNoRequi(idSurvey, answer.getIdQues(), dUserResponseItem) == Error.ERR_SYSTEM) {
                    return Error.ERR_SYSTEM;
                }

            }
        }
        // store iduser response
        dUserResponseItem = IDUserResponseData.getInstance().getIDUserResponseItem(idSurvey);
        if (dUserResponseItem == null) {
            dUserResponseItem = new IDUserResponseItem();
            listIDUser = new ArrayList<Integer>();
        } else {
            listIDUser = dUserResponseItem.getIdUsers();
        }
        listIDUser.add(0, idUser);
        dUserResponseItem.setIdUsers(listIDUser);
        if (IDUserResponseData.getInstance().setIDUserResponseItem(idSurvey, dUserResponseItem) == Error.ERR_SYSTEM) {
            return Error.ERR_SYSTEM;
        }
        // update state user
        if(ResponseData.getInstance().setResponse(idSurvey, idUser, response)!= Error.SUCCESS){
           return Error.ERR_SYSTEM;
        }
        // update stats survey
        SurveyStatsItem surveyStatsItem;
        surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idSurvey);
        if (surveyStatsItem == null) {
            surveyStatsItem = new SurveyStatsItem();
            surveyStatsItem.setView(0);
            surveyStatsItem.setResponse(0);
            surveyStatsItem.setIDUser(idUser);
        }
        surveyStatsItem.setResponse(surveyStatsItem.getResponse() + 1);
        Map<Short, QuestionStats> mapquestionstats = surveyStatsItem.getStats();
        if (mapquestionstats == null) {
            mapquestionstats = new HashMap<Short, QuestionStats>();
        }
        for (int i = 0; i < listAnswer.size(); i++) {
            short idQ = listAnswer.get(i).getIdQues();
            String[] choice = listAnswer.get(i).getAnswer().split(",");
            QuestionStats questionStats = new QuestionStats();
            questionStats.setType(listAnswer.get(i).getType());
            List<Integer> stats = null;
            if (mapquestionstats.get(idQ) != null) {

                stats = mapquestionstats.get(idQ).getNumber();
            } else {

                stats = new ArrayList<Integer>();
            }
            // cho tung cau hoi chua làm
            if (listAnswer.get(i).getType() == QuesType.SINGLE_LINE || listAnswer.get(i).getType() == QuesType.MULTI_LINE) {
                if (stats.size() == 0) {
                    stats.add(0, 1);
                } else {
                    stats.set(0, stats.get(0) + 1);

                }

            } else {
                for (int j = 0; j < choice.length; j++) {
                    if (stats.size() < choice.length) {
                        if (choice[j].equals("0")) {
                            stats.add(j, 0);
                        } else {
                            stats.add(j, 1);
                        }
                    } else {

                        if (choice[j].equals("1")) {
                            stats.set(j, stats.get(j) + 1);
                        }

                    }
                }

            }
            questionStats.setNumber(stats);
            mapquestionstats.put(listAnswer.get(i).getIdQues(), questionStats);
        }
        surveyStatsItem.setStats(mapquestionstats);
        if (SurveyStatsData.getInstance().setSurveyStatsItem(idSurvey, surveyStatsItem) == Error.ERR_SYSTEM) {
            return Error.ERR_SYSTEM;
        }

        return Error.SUCCESS;

     // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Error updateSurvey(int idSurvey, SurveyItem surveyItem) throws TException {
        SurveyItem surveyItem1 = SurveyData.getInstance().getSurvey(idSurvey);

        if (surveyItem1 == null) {
            return Error.IDSURVEY_NO_EXITS;

        }
        if (SurveyData.getInstance().setSurvey(idSurvey, surveyItem) == Error.ERR_SYSTEM) {
            return Error.ERR_SYSTEM;
        }
        return Error.SUCCESS;
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Map<Short, Integer> listQuesCanEdit(int idSurvey) throws TException {
        Map<Short,Integer> listQues = new HashMap<Short,Integer>();
        SurveyItem surveyItem = SurveyData.getInstance().getSurvey(idSurvey);
        if(surveyItem ==null){
         return null;
        }
        
         SurveyStatsItem surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idSurvey);
        
         if (surveyStatsItem == null) {
                surveyStatsItem = new SurveyStatsItem();
                surveyStatsItem.setView(0);
                surveyStatsItem.setResponse(0);
                SurveyStatsData.getInstance().setSurveyStatsItem(idSurvey, surveyStatsItem);
         }
        Map<Short, QuestionStats> mapquestionstats = surveyStatsItem.getStats();
         
        List<Question> list =surveyItem.getQuestions();
        for(Question question : list){
            if(mapquestionstats ==null){
                listQues.put(question.getIdQues(), 0);
            
            }else{
                if(question.require == true){
                    if(surveyStatsItem.getResponse()==0){
                            listQues.put(question.getIdQues(), 0);
                    }
                }else{
                    if(mapquestionstats.get(question.getIdQues())== null){
                         listQues.put(question.getIdQues(), 0);
                    }
                
                }
            
            }
        
        }
        return listQues;

        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<ShortInfoSurveyItem> getListShortInfoSurveyItem(int idUser, int page, int numOfpage) throws TException {
        List<ShortInfoSurveyItem> list = new ArrayList<ShortInfoSurveyItem>();
        // get list idsurvey
        IDSurveyItem dSurveyItem = IDSurveyData.getInstance().getIDSurveyItem(idUser);
        if (dSurveyItem == null) {
            return list;
        }
        int begin = page*numOfpage;
        int end   = begin+numOfpage;
        List<Integer> listIDSur = dSurveyItem.getIdSurveys();
        int sizeListIDSur =listIDSur.size();
        if((sizeListIDSur/numOfpage)<(page-1)){
              return list;
        }
        if(sizeListIDSur<end){
            end =sizeListIDSur;
        }
        for (int i = begin; i < end; i++) {
            int idsur = listIDSur.get(i);
            SurveyItem surveyItem = SurveyData.getInstance().getSurvey(idsur);
            if (surveyItem != null) {
                SurveyStatsItem surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idsur);
                if (surveyStatsItem != null) {

                    list.add(new ShortInfoSurveyItem(idsur, surveyItem.status, surveyStatsItem.getView(), surveyStatsItem.getResponse(), surveyItem.getTitle(), surveyItem.getDescription()));
                }

            }

        }

        return list;
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public SurveyItemResult getSurvey(int idSurvey) throws TException {
        SurveyItemResult itemResult = new SurveyItemResult();
        SurveyItem surveyItem = SurveyData.getInstance().getSurvey(idSurvey);
        if (surveyItem == null) {
            itemResult.setErro(Error.IDSURVEY_NO_EXITS);
            return itemResult;
        }
        itemResult.setErro(Error.SUCCESS);
        itemResult.setSurveyItem(surveyItem);
        return itemResult;
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int getCountSurvey(int idUser) throws TException {
        IDSurveyItem dSurveyItem = IDSurveyData.getInstance().getIDSurveyItem(idUser);
        if (dSurveyItem == null) {
            return 0;
        }
        return dSurveyItem.getCount();
        //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<AnswerItem> getResponse(int idSurvey, int idUser) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int getCountResponse(int idSurvey) throws TException {
        SurveyStatsItem surveyStatsItem;
        surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idSurvey);
        if (surveyStatsItem == null) {
            return 0;
        }
        return surveyStatsItem.getResponse();
        //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<Response> getListResponse(int idSurvey, int page, int numOfpage) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int getCountResByQues(int idSurvey, short idQues) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<AnswerItem> getResByQues(int idSurvey, short idQues, int page, int numOfpage) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public SurveyStatsResult getSurveyStats(int idSurvey) throws TException {
        SurveyStatsResult surveyStatsResult = new SurveyStatsResult();
        SurveyStatsItem surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idSurvey);
        if (surveyStatsItem == null) {
            surveyStatsResult.setErro(Error.IDSURVEY_NO_EXITS);
            return surveyStatsResult;
        }
        surveyStatsResult.setErro(Error.SUCCESS);
        surveyStatsResult.setSurveyStatsItem(surveyStatsItem);
        return surveyStatsResult;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public State checkUser(int idSurvey, int idUser) throws TException {
        Response response = ResponseData.getInstance().getResponse(idSurvey, idUser);
        
        if (response == null) {
            response = new Response();
            ResponseData.getInstance().setResponse(idSurvey, idUser, response);
            SurveyStatsItem surveyStatsItem;
            surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idSurvey);
            if (surveyStatsItem == null) {
                surveyStatsItem = new SurveyStatsItem();
                surveyStatsItem.setView(0);
                surveyStatsItem.setResponse(0);
                surveyStatsItem.setIDUser(idUser);
            }
            surveyStatsItem.setView(surveyStatsItem.getView() + 1);
            SurveyStatsData.getInstance().setSurveyStatsItem(idSurvey, surveyStatsItem);
            return State.NEW;
        }
        return State.VIEW;
        //   throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Error removeSurveyItem(int idSurvey) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<Error> removeListSurveyItem(List<Integer> idSurveys) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Error removeResponse(int idSurvey, int idUser) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Error removeListResponse(List<ResponseKey> responseKey) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public String getStat(int type) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}
